import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Tag,
  Progress,
  Divider,
  Space
} from 'tdesign-react';
import {
  PlayIcon,
  DashboardIcon,
  TimeIcon,
  GiftIcon,
  StarIcon,
  BookIcon
} from 'tdesign-icons-react';

const AchievementsContainer: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <div style={{
    background: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
    borderRadius: '20px',
    padding: '24px',
    minHeight: '95vh',
    width: '100%',
    maxWidth: '100%',
    color: '#fff',
    margin: 0,
    boxSizing: 'border-box'
  }}>
    {children}
  </div>
);

const StatsCard: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <div 
    style={{
      background: 'linear-gradient(45deg, #3498db 30%, #2980b9 90%)',
      borderRadius: '15px',
      color: '#fff',
      margin: '8px',
      transition: 'transform 0.2s ease-in-out',
      padding: '16px',
      textAlign: 'center',
      cursor: 'pointer'
    }}
    onMouseEnter={(e) => {
      e.currentTarget.style.transform = 'translateY(-4px)';
    }}
    onMouseLeave={(e) => {
      e.currentTarget.style.transform = 'translateY(0)';
    }}
  >
    {children}
  </div>
);

const HistoryCard: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <Card 
    style={{
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderRadius: '12px',
      margin: '8px 0',
      boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
      padding: '16px'
    }}
  >
    {children}
  </Card>
);

interface TypingRecord {
  id: string;
  date: string;
  difficulty: 'easy' | 'medium' | 'hard';
  wpm: number;
  accuracy: number;
  completionTime: number;
  score: number;
}

const AchievementsView: React.FC = () => {
  const [records, setRecords] = useState<TypingRecord[]>([]);
  const [stats, setStats] = useState({
    totalSessions: 0,
    bestWpm: 0,
    bestAccuracy: 0,
    averageWpm: 0,
    averageAccuracy: 0,
    totalTime: 0
  });

  useEffect(() => {
    // 从 localStorage 加载历史记录
    const savedRecords = localStorage.getItem('typingRecords');
    if (savedRecords) {
      const parsedRecords: TypingRecord[] = JSON.parse(savedRecords);
      setRecords(parsedRecords);
      calculateStats(parsedRecords);
    }
  }, []);

  const calculateStats = (recordList: TypingRecord[]) => {
    if (recordList.length === 0) {
      setStats({
        totalSessions: 0,
        bestWpm: 0,
        bestAccuracy: 0,
        averageWpm: 0,
        averageAccuracy: 0,
        totalTime: 0
      });
      return;
    }

    const totalSessions = recordList.length;
    const bestWpm = Math.max(...recordList.map(r => r.wpm));
    const bestAccuracy = Math.max(...recordList.map(r => r.accuracy));
    const averageWpm = Math.round(recordList.reduce((sum, r) => sum + r.wpm, 0) / totalSessions);
    const averageAccuracy = Math.round(recordList.reduce((sum, r) => sum + r.accuracy, 0) / totalSessions);
    const totalTime = recordList.reduce((sum, r) => sum + r.completionTime, 0);

    setStats({
      totalSessions,
      bestWpm,
      bestAccuracy,
      averageWpm,
      averageAccuracy,
      totalTime
    });
  };

  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty) {
      case 'easy': return '#27ae60';
      case 'medium': return '#f39c12';
      case 'hard': return '#e74c3c';
      default: return '#95a5a6';
    }
  };

  const getPerformanceLevel = (wpm: number, accuracy: number) => {
    if (wpm >= 40 && accuracy >= 95) return { level: '大师', color: '#f1c40f' };
    if (wpm >= 30 && accuracy >= 90) return { level: '专家', color: '#e74c3c' };
    if (wpm >= 20 && accuracy >= 85) return { level: '熟练', color: '#3498db' };
    if (wpm >= 15 && accuracy >= 80) return { level: '良好', color: '#27ae60' };
    return { level: '初学', color: '#95a5a6' };
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <AchievementsContainer>
      <div style={{ textAlign: 'center', marginBottom: '32px' }}>
        <h1 style={{ fontSize: '2.5rem', margin: '0 0 16px 0', color: '#fff' }}>
          🏆 成就与统计
        </h1>
        <h3 style={{ fontSize: '1.25rem', opacity: 0.9, margin: 0, color: '#fff', fontWeight: 'normal' }}>
          记录你的每一次进步
        </h3>
      </div>

      {/* 整体统计 */}
      <Row gutter={16} style={{ marginBottom: '32px' }}>
        <Col xs={12} sm={6} md={4}>
          <StatsCard>
            <GiftIcon size="2rem" style={{ marginBottom: '8px' }} />
            <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#fff' }}>{stats.totalSessions}</div>
            <div style={{ fontSize: '0.875rem', color: '#fff' }}>总练习次数</div>
          </StatsCard>
        </Col>
        <Col xs={12} sm={6} md={4}>
          <StatsCard>
            <PlayIcon size="2rem" style={{ marginBottom: '8px' }} />
            <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#fff' }}>{stats.bestWpm}</div>
            <div style={{ fontSize: '0.875rem', color: '#fff' }}>最高速度 WPM</div>
          </StatsCard>
        </Col>
        <Col xs={12} sm={6} md={4}>
          <StatsCard>
            <DashboardIcon size="2rem" style={{ marginBottom: '8px' }} />
            <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#fff' }}>{stats.bestAccuracy}%</div>
            <div style={{ fontSize: '0.875rem', color: '#fff' }}>最高准确率</div>
          </StatsCard>
        </Col>
        <Col xs={12} sm={6} md={4}>
          <StatsCard>
            <BookIcon size="2rem" style={{ marginBottom: '8px' }} />
            <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#fff' }}>{stats.averageWpm}</div>
            <div style={{ fontSize: '0.875rem', color: '#fff' }}>平均速度 WPM</div>
          </StatsCard>
        </Col>
        <Col xs={12} sm={6} md={4}>
          <StatsCard>
            <StarIcon size="2rem" style={{ marginBottom: '8px' }} />
            <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#fff' }}>{stats.averageAccuracy}%</div>
            <div style={{ fontSize: '0.875rem', color: '#fff' }}>平均准确率</div>
          </StatsCard>
        </Col>
        <Col xs={12} sm={6} md={4}>
          <StatsCard>
            <TimeIcon size="2rem" style={{ marginBottom: '8px' }} />
            <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#fff' }}>{Math.round(stats.totalTime / 60)}</div>
            <div style={{ fontSize: '0.875rem', color: '#fff' }}>总练习时间(分)</div>
          </StatsCard>
        </Col>
      </Row>

      <Divider style={{ backgroundColor: 'rgba(255,255,255,0.2)', margin: '24px 0' }} />

      {/* 历史记录 */}
      <div>
        <h2 style={{ color: '#fff', marginBottom: '24px', fontSize: '2rem', fontWeight: 'bold' }}>
          📈 练习历史
        </h2>
        
        {records.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '32px 0' }}>
            <h3 style={{ opacity: 0.7, color: '#fff', fontWeight: 'normal' }}>
              还没有练习记录，开始你的第一次练习吧！
            </h3>
          </div>
        ) : (
          <div style={{ maxHeight: '500px', overflow: 'auto' }}>
            {records.slice().reverse().map((record, index) => {
              const performance = getPerformanceLevel(record.wpm, record.accuracy);
              return (
                <HistoryCard key={record.id}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                        <h3 style={{ color: '#2c3e50', fontWeight: 'bold', margin: 0, fontSize: '1.25rem' }}>
                          第 {records.length - index} 次练习
                        </h3>
                        <Tag 
                          theme="primary"
                          style={{ 
                            backgroundColor: getDifficultyColor(record.difficulty),
                            color: '#fff',
                            fontWeight: 'bold',
                            border: 'none'
                          }}
                        >
                          {record.difficulty.toUpperCase()}
                        </Tag>
                        <Tag 
                          theme="primary"
                          style={{ 
                            backgroundColor: performance.color,
                            color: '#fff',
                            fontWeight: 'bold',
                            border: 'none'
                          }}
                        >
                          {performance.level}
                        </Tag>
                      </div>
                      <div style={{ color: '#666', fontSize: '0.875rem' }}>
                        {formatDate(record.date)}
                      </div>
                    </div>
                    
                    <Row gutter={24}>
                      <Col span={6}>
                        <div style={{ textAlign: 'center' }}>
                          <div style={{ color: '#3498db', fontWeight: 'bold', fontSize: '1.5rem' }}>
                            {record.wpm}
                          </div>
                          <div style={{ color: '#666', fontSize: '0.875rem' }}>
                            WPM
                          </div>
                        </div>
                      </Col>
                      <Col span={6}>
                        <div style={{ textAlign: 'center' }}>
                          <div style={{ color: '#27ae60', fontWeight: 'bold', fontSize: '1.5rem' }}>
                            {record.accuracy}%
                          </div>
                          <div style={{ color: '#666', fontSize: '0.875rem' }}>
                            准确率
                          </div>
                        </div>
                      </Col>
                      <Col span={6}>
                        <div style={{ textAlign: 'center' }}>
                          <div style={{ color: '#f39c12', fontWeight: 'bold', fontSize: '1.5rem' }}>
                            {record.completionTime}s
                          </div>
                          <div style={{ color: '#666', fontSize: '0.875rem' }}>
                            完成时间
                          </div>
                        </div>
                      </Col>
                      <Col span={6}>
                        <div style={{ textAlign: 'center' }}>
                          <div style={{ color: '#e74c3c', fontWeight: 'bold', fontSize: '1.5rem' }}>
                            {record.score}
                          </div>
                          <div style={{ color: '#666', fontSize: '0.875rem' }}>
                            总分
                          </div>
                        </div>
                      </Col>
                    </Row>
                    
                    {/* 进度条显示相对表现 */}
                    <div style={{ marginTop: '16px' }}>
                      <div style={{ color: '#666', marginBottom: '4px', fontSize: '0.875rem' }}>
                        相对最佳表现
                      </div>
                      <Progress 
                        percentage={stats.bestWpm > 0 ? Math.round((record.wpm / stats.bestWpm) * 100) : 0}
                        strokeWidth={6}
                        theme="line"
                      />
                    </div>
                </HistoryCard>
              );
            })}
          </div>
        )}
      </div>
    </AchievementsContainer>
  );
};

export default AchievementsView;